package abc.config.interceptor;

import abc.database.DataExecuor;
import abc.filter.RequestMatchSchemaFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.Map;

@Component
@Qualifier("sqlInterceptor")
public class SqlInterceptor implements InnerInterceptor {
    @Autowired
    RequestMatchSchemaFilter requestMatchSchemaFilter;
    @Autowired
    protected DataExecuor dataExecuor;

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        //step1. 查询是否存在需要构建高级查询的参数 ，如果没有就直接返回
        QueryWrapper queryWrapper = (QueryWrapper)((Map)parameter).get("ew");
        // 没有参数直接返回
        if (null == queryWrapper) {
            return;
        }
        String table = requestMatchSchemaFilter.getTableName();
        var model = dataExecuor.getModel(table);
        //step2. 获取到当前需要执行的sql
        String buildSql = boundSql.getSql();
        //step3. 拼接查询条件
        buildSql = String.format("select temp.* from ( %s ) as temp where  %s ", buildSql, "1=1");
        //排序sql
//        if(StringUtils.isNotEmpty(swaQueryParam.getColumn())) {
//            buildSql = String.format("%s order by %s %s",buildSql, oConvertUtils.camelToUnderline(swaQueryParam.getColumn()),StringUtils.defaultString(swaQueryParam.getOrder(), "desc"));
//        }
        //修改完成的sql 再设置回去
        PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
        mpBoundSql.sql(buildSql);
    }
}
